<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'; // 引入 useRouter
import CryptoJS from 'crypto-js';
// References
const ruleFormRef = ref<FormInstance>()
// 创建路由对象，用于编程式导航
const router = useRouter()
// 密码校验(第一个新密码)
const validatePass = (rule: any, value: any, callback: any) => {
    // 校验长度
    const lengthPattern = /^.{8,12}$/; // 至少8位，最多12位
    if (!lengthPattern.test(value)) {
        callback(new Error('密码长度必须在 8 到 12 位之间'));
        return;
    }

    // // 校验首字符为字母
    // const firstCharPattern = /^[a-zA-Z]/;
    // if (!firstCharPattern.test(value)) {
    //     callback(new Error('密码的首字符必须是英文字母'));
    //     return;
    // }

    // 校验必须包含字母、数字和特殊字符
    const complexityPattern = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]+$/;
    if (!complexityPattern.test(value)) {
        callback(new Error('密码必须包含至少一个字母、一个数字和一个特殊字符'));
        return;
    }

    // 如果确认密码不为空，则验证确认密码
    if (ruleForm.checkPass !== '') {
        if (!ruleFormRef.value) return
        ruleFormRef.value.validateField('checkPass')
    }
    callback()
}

// 确认密码校验(第二个新密码)
const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请重新输入密码'))
    } else if (value !== ruleForm.newpass) {
        callback(new Error("两次输入不一致!"))
    } else {
        callback()
    }
}

// Reactive form data
const ruleForm = reactive({
    oldPass: '',
    newpass: '', // 新密码
    checkPass: '', // 确认密码
})

// Validation rules
const rules = reactive<FormRules<typeof ruleForm>>({
    oldPass: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newpass: [{ validator: validatePass, trigger: 'blur' }],
    checkPass: [{ validator: validatePass2, trigger: 'blur' }],
})



//忘记密码按钮
const forgotpass = () => {
    //跳转忘记密码页面
    router.push('/staging/forgotpass')
}

// Reset form
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//解密token
function getToken() {
    const encryptedToken = localStorage.getItem('token');
    if (encryptedToken) {
        const secretKey = 'your_secret_key'; // 使用相同的密钥
        const bytes = CryptoJS.AES.decrypt(encryptedToken, secretKey);
        const decryptedToken = bytes.toString(CryptoJS.enc.Utf8);
        return decryptedToken;
    }
    return null;
}

//提交表单,修改密码
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log('submit!')
            const token = getToken();
            if (token) {
                const data = {
                    oldPassword: ruleForm.oldPass,
                    newPassword: ruleForm.newpass,
                    token: token
                }
                console.log(data)
                // 发送请求到后端进行密码修改
                fetch('http://localhost:8080/user/changepassword', {
                    method: 'POST',
                    body: JSON.stringify(data),
                    headers: {
                       'Content-Type': 'application/json',
                       Authorization: 'Bearer ' + token
                    },
                })
                .then(response => response.json())      // 解析响应数据
                .then(data => {
                    console.log(data)
                    if (data.code == '200') {
                        ElMessage({
                            message: '密码修改成功',
                            type: 'success',
                            plain: true
                        })
                        // 重定向到登录页面
                        router.push('/login')
                    }else {}
                })
            }else {
                alert('登录失效，请重新登录')
                router.push('/login')
            }
        } else {
            console.log('error submit!')
        }
    })
}

</script>

<template>
    <div class="container">
        <el-form ref="ruleFormRef" style="max-width: 600px; width: 100%" :model="ruleForm" status-icon :rules="rules"
            label-width="auto" class="demo-ruleForm">
            <h1 class="form-title">密码重置</h1>
            <el-form-item label="请输入旧密码" prop="oldPass">
                <el-input v-model="ruleForm.oldPass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="请输入新密码" prop="newpass">
                <el-input v-model="ruleForm.newpass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="请重新输入新密码" prop="checkPass">
                <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
            </el-form-item>
                 <el-divider content-position="center"></el-divider>            
            <el-form-item class="button-container" style="text-align: center;">
                <div style="display: inline-flex; gap: 10px;"> <!-- 使用 inline-flex 添加间距 -->
                    <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                    <el-button @click="forgotpass">忘记密码</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<style scoped>
.container {

    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
     /* 背景模糊效果 */
     background: rgba(255, 255, 255, 0.5); /* 半透明背景 */
    backdrop-filter: blur(15px); /* 模糊背景 */
}

.form-title {
    text-align: center; /* 标题居中 */
    width: 100%; /* 使标题占据 100% 宽度 */
}

.button-container {
    text-align: center; /* 按钮块居中 */
    margin-top: 20px; /* 可选：添加按钮的上方间距 */
}
</style>
